package cn.itcast.dtx.tccdemo.bank2.service.impl;

import cn.itcast.dtx.tccdemo.bank2.dao.AccountInfoDao;
import cn.itcast.dtx.tccdemo.bank2.service.AccountInfoService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.Hmily;
import org.dromara.hmily.core.concurrent.threadlocal.HmilyTransactionContextLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Slf4j
public class AccountInfoServiceImpl implements AccountInfoService {
    @Autowired
    AccountInfoDao accountInfoDao;

    /**
     * 更新账户余额
     *
     * @param accountNo
     * @param amount
     */
    @Transactional
    @Hmily(confirmMethod = "confirmUpdateAccountBlance", cancelMethod = "cancelUpdateAccountBlance")
    @Override
    public void updateAccountBlance(String accountNo, Double amount) {
        //获取全局事物id localTradeNo
        final String localTradeNo = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("updateAccountBlance开始执行，更新账户余额，事物id:{}", localTradeNo);
    }

    /**
     * 确认阶段 进行数据更新操作
     * 这里只要
     * 1、幂等校验
     * 2、正式增加金额
     *
     * @param accountNo
     * @param amount
     */
    @Transactional
    public void confirmUpdateAccountBlance(String accountNo, Double amount) {
        final String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("confirmUpdateAccountBlance确认阶段开始执行，全局事物id:{}", transId);
        // 幂等校验
        if(accountInfoDao.isExistConfirm(transId)>0){
            log.info("confirmUpdateAccountBlance确认阶段已经执行，无需重复执行全局事物id:{}", transId);
        }
        //正式增加金额
        final int result = accountInfoDao.addAccountBalance(accountNo, amount);
        log.info("confirmUpdateAccountBlance执行确认阶段执行addAccountBalance结果：【{}】，账户【{}】，增加金额【{}】，事物id:{}"
                , result, accountNo, amount,transId);
        //添加confirm日志
        accountInfoDao.addConfirm(transId);
    }

    /**
     * 取消阶段 进行数据回滚操作
     *
     * @param accountNo
     * @param amount
     */
    public void cancelUpdateAccountBlance(String accountNo, Double amount) {
        final String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("cancelUpdateAccountBlance取消阶段开始执行，全局事物id:{}", transId);
    }
}
